package com.xiaofen.license;

import com.xiaofen.license.util.SpringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.ContextStartedEvent;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class LicenseApplication {

    public static void main(String[] args) {
        Map<String, Object> defaultProp = new HashMap<>();

        SpringApplication springApplication = new SpringApplication(LicenseApplication.class);
        springApplication.setDefaultProperties(defaultProp);


        ConfigurableApplicationContext context = springApplication.run(args);
        SpringUtils.setFactory(context);
        context.publishEvent(new ContextStartedEvent(context));

        String appName = context.getEnvironment().getProperty("spring.application.name");
        String pid = context.getEnvironment().getProperty("PID");
        //注意:本启动类不应先加载Logger，优先让spring去初始化Logger的配置，否则日志输出会异常
        LoggerFactory.getLogger(LicenseApplication.class).info(StringUtils.center("应用程序[{}]启动完毕,LIC_PID={}", 60, "+"), appName, pid);
    }

    /**
     * 非开发环境运行时，输出pid进程号文件，用于查杀进程。备注，只有在系统正常启动完毕后才会生成
     * @return
     */
    @Bean
    @Profile({"!dev"})
    public ApplicationPidFileWriter pidFile(){
        ApplicationPidFileWriter w = new ApplicationPidFileWriter();
        //监听spring正常启动完毕时间，这个阶段才生成pid文件
        w.setTriggerEventType(ApplicationReadyEvent.class);
        return w;
    }

}
